package logic

import (
	"api/internal/svc"
	"context"
	"encoding/json"
	"fmt"
	"github.com/gorilla/websocket"
	"github.com/zeromicro/go-zero/core/logx"
	"io/ioutil"
	"net/http"
	"strconv"
	"strings"
)

type TestLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewTestLogic(ctx context.Context, svcCtx *svc.ServiceContext) *TestLogic {
	return &TestLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

type MerCreateResp struct {
	Msg     string `json:"msg"`
	OrderId string `json:"order_id"`
}

type TTSResponse struct {
	Binary string `json:"binary"`
}

func (l *TestLogic) Test() (string, error) {
	///////// 支付宝

	// 支付宝 h5支付

	// h5 下单
	//client, err := alipay.NewClient(cert.AliAPPID, cert.AliPrivateKey, true)
	//if err != nil {
	//	l.Error(err)
	//	return nil
	//}
	//client.AutoVerifySign(cert.AliPublicRSA2)   // 自动验签 待测
	//err = client.SetCertSnByContent(cert.AliAppCer, cert.AliRootCer, cert.AliPublicCer)
	//if err != nil {
	//	l.Error("SetCertSn:", err)
	//	return nil
	//}
	////配置公共参数
	//client.SetCharset("utf-8").
	//	SetSignType(alipay.RSA2).
	//	SetNotifyUrl("https://unionpay.vip.cpolar.cn/notify/alipay")
	////请求参数
	//bm := make(gopay.BodyMap)
	//bm.Set("subject", "手机网站测试支付")
	//bm.Set("out_trade_no", "GZ202001301040357322") //  只返回 支付宝交易凭证号2024042822001491981400653292
	//bm.Set("quit_url", "https://www.fmm.ink")      //  取消支付时返回的界面
	//bm.Set("total_amount", "0.1")
	//bm.Set("product_code", "QUICK_WAP_WAY")
	////手机网站支付请求
	//payUrl, err := client.TradeWapPay(l.ctx, bm)
	//if err != nil {
	//	l.Error("err:", err)
	//	return nil
	//}
	//fmt.Println("payUrl:", payUrl)

	// 转账到个人支付宝
	//client, err := alipay.NewClient(cert.AliTransferAPPID, cert.AlitransferPrivateKey, true)
	//if err != nil {
	//	l.Error(err)
	//	return nil
	//}
	//err = client.SetCertSnByContent(cert.AliTransferAppCer, cert.AliTransferRootCer, cert.AliTransferPublicCer)
	//if err != nil {
	//	l.Error("SetCertSn:", err)
	//	return nil
	//}
	////配置公共参数
	//client.SetCharset("utf-8").
	//	SetSignType(alipay.RSA2)
	//bm := make(gopay.BodyMap)
	//bm.Set("out_biz_no", "201806300011232305").
	//	Set("trans_amount", "1000").
	//	Set("biz_scene", "DIRECT_TRANSFER").
	//	Set("product_code", "TRANS_ACCOUNT_NO_PWD").
	//	SetBodyMap("payee_info", func(bm gopay.BodyMap) {
	//		bm.Set("identity_type", "ALIPAY_LOGON_ID")
	//		bm.Set("name", "吴海生") //identity_type 为 ALIPAY_LOGON_ID 时必填
	//		bm.Set("identity", "16608971293")
	//	})
	//
	//aliRsp, err := client.FundTransUniTransfer(l.ctx, bm)
	//if err != nil {
	//	l.Error(err)
	//	return nil
	//}
	//fmt.Println("aliRsp:", *aliRsp)
	//fmt.Println("aliRsp.Response:", aliRsp.Response)

	// 支付宝进件二级商户
	//client, err := alipay.NewClient(cert.AliAPPID, cert.AliPrivateKey, true)
	//if err != nil {
	//	l.Error(err)
	//	return nil
	//}
	////client.AutoVerifySign(cert.AliPublicRSA2) // 自动验签 待测
	//err = client.SetCertSnByContent(cert.AliAppCer, cert.AliRootCer, cert.AliPublicCer)
	//if err != nil {
	//	l.Error("SetCertSn:", err)
	//	return nil
	//}
	//bm := make(gopay.BodyMap)
	//
	//// biz_content
	////externalId := service.GenerateUniqueID(32)
	////jsonD, _ := json.Marshal([]string{"jsapi"})
	//bm.Set("binding_alipay_logon_id", "16608971293").
	//	Set("external_id", "12345").
	//	Set("alias_name", "测试店铺").
	//	SetBodyMap("contact_infos", func(bm gopay.BodyMap) {
	//		bm.Set("name", "北京烤鸭")
	//		bm.Set("phone", "16608971293")
	//	}).
	//	SetBodyMap("default_settle_rule", func(bm gopay.BodyMap) {
	//		bm.Set("default_settle_type", "bankCard")
	//		bm.Set("default_settle_target", "银行卡卡号")
	//	}).
	//	//Set("service", "['jsapi']").
	//	Set("mcc", "B0007").
	//	SetBodyMap("biz_cards", func(bm gopay.BodyMap) {
	//		bm.Set("account_holder_name", "张三")
	//		bm.Set("account_no", "6214855710610408")
	//		bm.Set("account_inst_province", "浙江省")
	//		bm.Set("account_inst_city", "杭州市")
	//		bm.Set("account_branch_name", "招商银行杭州高新支行")
	//		bm.Set("usage_type", "02")
	//		bm.Set("account_inst_name", "招商银行")
	//		bm.Set("account_inst_id", "CMB")
	//	})
	//var resp interface{}
	//err = client.PostAliPayAPISelfV2(l.ctx, bm, "ant.merchant.expand.indirect.zft.simplecreate", &resp)
	//if err != nil {
	//	fmt.Println("=======报错了==========")
	//	fmt.Println(err)
	//	return nil
	//}
	//fmt.Println("没错")
	//fmt.Println(resp)

	// 微信app支付

	// app创单
	//client, err := wechat.NewClientV3(cert.WxMchid, cert.WxSerialNo, cert.WxApiV3Key, cert.WxPrivateKey)
	//if err != nil {
	//	l.Error(err)
	//	return nil
	//}
	//
	//// 设置微信平台API证书和序列号（推荐开启自动验签，无需手动设置证书公钥等信息）
	////client.SetPlatformCert([]byte(""), "")
	//
	//// 启用自动同步返回验签，并定时更新微信平台API证书（开启自动验签时，无需单独设置微信平台API证书和序列号）
	//err = client.AutoVerifySign()
	//if err != nil {
	//	l.Error(err)
	//	return nil
	//}
	//
	//tradeNo := util.RandomString(32)
	//xlog.Debug("tradeNo:", tradeNo)
	//expire := time.Now().Add(10 * time.Minute).Format(time.RFC3339)
	//
	//bm := make(gopay.BodyMap)
	//bm.Set("sp_appid", cert.WxAppId).
	//	Set("sp_mchid", "sp_mchid").
	//	Set("sub_mchid", "sub_mchid").
	//	Set("description", "测试Jsapi支付商品").
	//	Set("out_trade_no", tradeNo).
	//	Set("time_expire", expire).
	//	Set("notify_url", "https://www.fmm.ink").
	//	SetBodyMap("amount", func(bm gopay.BodyMap) {
	//		bm.Set("total", 1).
	//			Set("currency", "CNY")
	//	}).
	//	SetBodyMap("payer", func(bm gopay.BodyMap) {
	//		bm.Set("sp_openid", "asdas")
	//	})
	//
	//wxRsp, err := client.V3PartnerTransactionJsapi(l.ctx, bm)
	//if err != nil {
	//	l.Error(err)
	//	return nil
	//}
	//if wxRsp.Code == 200 {
	//	fmt.Println("wxRsp: %+v", wxRsp.Response)
	//	return nil
	//}
	//l.Error("wxRsp:%s", wxRsp.Error)

	// app支付

	// 文本转语音
	//url := "https://tsn.baidu.com/text2audio"
	//text := url2.QueryEscape(url2.QueryEscape("支付宝收款200元"))
	//params := "&cuid=VaqnCfA3jtCU4jdvyZ8SULxSeE212RZZ&ctp=1&lan=zh&spd=5&pit=3&vol=14&per=5118&aue=3"
	//
	//payload := strings.NewReader("tex=" + text + "&tok=" + GetAccessToken(l.svcCtx.Config.BaiduTTS.APIKey, l.svcCtx.Config.BaiduTTS.SecretKey) + params)
	//client := &http.Client{}
	//req, err := http.NewRequest("POST", url, payload)
	//
	//if err != nil {
	//	fmt.Println(err)
	//	return "", nil
	//}
	//req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
	//req.Header.Add("Accept", "*/*")
	//
	//res, err := client.Do(req)
	//if err != nil {
	//	fmt.Println(err)
	//	return "", nil
	//}
	//defer res.Body.Close()
	//
	//body, err := ioutil.ReadAll(res.Body)
	//if err != nil {
	//	fmt.Println(err)
	//	return "", nil
	//}
	//var r TTSResponse
	//json.Unmarshal(body, &r)
	//return string(body), nil

	socket := l.svcCtx.WebSocketPool.Get()

	//data := map[string]string{
	//	"to_id": "7f0000010b5500000001",
	//	"msg":   "微信收款25.08元",
	//	"code":  "sendMsg",
	//}
	//jsonD, _ := json.Marshal(data)

	result, _ := fmt.Printf("%.2f\n", float64(1200)/float64(100))

	d := map[string]string{
		"voice":       "微信收款" + strconv.Itoa(result) + "元", // 收款信息
		"money_all":   "1200",
		"money_today": "1300",
	}

	jsonD, _ := json.Marshal(d)

	data := map[string]string{
		"to_id": "7f0000010b5400000014",
		"data":  string(jsonD),
		"code":  "sendMsg",
	}

	jsonD, _ = json.Marshal(data)

	socket.WriteMessage(websocket.TextMessage, jsonD)

	return "", nil

}
func GetAccessToken(apiKey string, secretKey string) string {
	url := "https://aip.baidubce.com/oauth/2.0/token"
	postData := fmt.Sprintf("grant_type=client_credentials&client_id=%s&client_secret=%s", apiKey, secretKey)
	resp, err := http.Post(url, "application/x-www-form-urlencoded", strings.NewReader(postData))
	if err != nil {
		fmt.Println(err)
		return ""
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println(err)
		return ""
	}
	accessTokenObj := map[string]any{}
	_ = json.Unmarshal(body, &accessTokenObj)
	return accessTokenObj["access_token"].(string)
}
